package com.ywyt.topic;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import com.ywyt.util.ConnUtil;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class TopicProvider {
    public static final String EX_NAME = "topic_ex";
    /*
    * routingKey
    * */
    public static final String RT_KEY = "topic.provider.order";

    @Test
    public void publish() throws IOException, TimeoutException, InterruptedException {
        //获取连接对象
        Connection conn = ConnUtil.getConnection();
        //获取channel
        Channel channel = conn.createChannel();
        //声明exchange
        channel.exchangeDeclare(EX_NAME, BuiltinExchangeType.TOPIC);


        //开启confirm
        channel.confirmSelect();

        //异步处理
        channel.basicPublish(EX_NAME,RT_KEY,null,"topic消息".getBytes());

        channel.addConfirmListener(new ConfirmListener() {
            @Override
            public void handleAck(long l, boolean b) throws IOException {
                System.out.println("消息发送成功");
            }

            @Override
            public void handleNack(long l, boolean b) throws IOException {
                System.out.println("消息发送失败");
            }
        });

        /*//批量消息
        for (int i = 0; i<10;i++){
            channel.basicPublish(EX_NAME,RT_KEY,null,("topic消息"+i).getBytes());
        }
        try {
            channel.waitForConfirmsOrDie();
            System.out.println("消息发送成功");
        } catch (IOException | InterruptedException e ) {
            e.printStackTrace();
            System.out.println("消息发送失败");
        }*/




        /*//单个消息
        //发布消息
        channel.basicPublish(EX_NAME,RT_KEY,null,"topic消息".getBytes());
        //确定消息是否发送成功
        if (channel.waitForConfirms()){
            System.out.println("消息发送成功");
        }else {
            System.out.println("消息发送失败");
        }
*/
        //释放资源
        channel.close();
        conn.close();
    }
}
